package com.jx.medical.controller;

import com.jx.medical.pojo.AjaxInfo;
import com.jx.medical.pojo.Instorage;
import com.jx.medical.pojo.Medicine;
import com.jx.medical.pojo.Outstorage;
import com.jx.medical.service.AdminService;
import com.jx.medical.service.TakeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author jx
 * @date Created on 2020/12/4  10:28
 **/
@RestController
@CrossOrigin
@RequestMapping("/take")
public class TakeController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private TakeService takeService;
    @RequestMapping("/insertStorage")
    public AjaxInfo outStroage(@RequestBody Outstorage outstorage, HttpSession session) {
        AjaxInfo ajaxInfo = new AjaxInfo();
        Outstorage o1 = new Outstorage();
        if (session.getAttribute("userName") != null) {
            Medicine med = adminService.getMedicineBymedId(outstorage.getMedId());
            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (med == null) {
                ajaxInfo.setCode(-1);
                ajaxInfo.setMsg("出库失败，该药品不存在！");
            } else {
                if (med.getMedStorage()>=outstorage.getOutStorageNum()) {
                    o1.setMedId(outstorage.getMedId());
                    o1.setPatientId(outstorage.getPatientId());
                    o1.setOutStorageNum(outstorage.getOutStorageNum());
                    o1.setOutDate(time.format(new Date()));
                    adminService.updateMedStorage(med.getMedId(), med.getMedStorage()-outstorage.getOutStorageNum());
                    ajaxInfo.setMsg("取药成功");
                    ajaxInfo.setCode(0);
                    takeService.insertOutStorage(o1);
                }else{
                    ajaxInfo.setCode(-1);
                    ajaxInfo.setMsg("取药数量大于库存量，请重新输入！该药品当前库存量为："+med.getMedStorage());
                }
                return ajaxInfo;
            }
            return ajaxInfo;

        } else {
            ajaxInfo.setMsg("权限不足！请先登录~");
        }
        return ajaxInfo;
    }
}
